package com.kinon.tyjaccount.view;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kinon.tyjaccount.Constatus;
import com.kinon.tyjaccount.R;
import com.kinon.tyjaccount.sqlitebean.BaseOrder;
import com.kinon.tyjaccount.sqlitebean.OrderBean;
import com.kinon.tyjaccount.sqlitebean.OrderDetail;
import com.kinon.tyjaccount.sqlitebean.SettletmentBean;
import com.kinon.tyjaccount.tools.CustomDialog;
import com.kinon.tyjaccount.tools.HttpTools;
import com.kinon.tyjaccount.tools.MyShowDialog;
import com.kinon.tyjaccount.tools.NetWorkUtil;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.io.File;
import java.util.ArrayList;

//import android.util.Log;

/**
 * Created by luohao on 2017-07-26.
 */

public class UrgentSetActivity extends Activity implements View.OnClickListener{

    private TextView tv_back;
    private TextView btn_urgentOn;
    private TextView btn_pullOrder;
    private TextView btn_pushLunch;
    private TextView btn_pushMakemeal;
    private TextView btn_clearLunch;
    private TextView btn_clearMake;

    private HttpTools httpTools=null;

    //自定义登陆广播Action
    public static final String LOGIN_ACTION = "ON_URGENT";

    private String token;
    private boolean isLunch=false;

    private File sqlfile=null;
    private File filename=null;

    private final String file_path= "/sdcard/account_app";
//    private final String file_name="/settle.txt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_urgentset_layout);
        initView();
    }
    private void initView() {
        tv_back= (TextView) findViewById(R.id.tv_back);
        btn_urgentOn= (TextView) findViewById(R.id.btn_urgentOn);
        btn_pullOrder= (TextView) findViewById(R.id.btn_pullOrder);
        btn_pushLunch= (TextView) findViewById(R.id.btn_pushLunch);
        btn_pushMakemeal= (TextView) findViewById(R.id.btn_pushMakemeal);
        btn_clearLunch= (TextView) findViewById(R.id.btn_clearLunch);
        btn_clearMake= (TextView) findViewById(R.id.btn_clearMake);

        //创建文件夹
//        createFile();

        SharedPreferences sp = getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
         token = sp.getString("data", "");

        if(Constatus.URGENT_TYPE){
            btn_urgentOn.setText("关闭紧急模式");

        }else{
            btn_urgentOn.setText("开启紧急模式");
        }
//        getOrderId();
        setOnclick();
    }
    private void setOnclick(){
        tv_back.setOnClickListener(this);
        btn_urgentOn.setOnClickListener(this);
        btn_pullOrder.setOnClickListener(this);
        btn_pushLunch.setOnClickListener(this);
        btn_pushMakemeal.setOnClickListener(this);
        btn_clearLunch.setOnClickListener(this);
        btn_clearMake.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_back:
                finish();
                break;
            case R.id.btn_urgentOn:
                urgentOn();
                break;
            case R.id.btn_pullOrder:
                getMakemealInfo();
                break;
            case R.id.btn_pushLunch:  //上传午餐信息
                pushLunch();
                break;
            case R.id.btn_pushMakemeal:
                pushMakemeal();
                break;
            case R.id.btn_clearLunch:
                clearSqlite(SettletmentBean.class,"是否清空本地结算和午餐信息");
                break;
            case R.id.btn_clearMake:
                clearSqlite(OrderBean.class,"是否清空本地取餐信息");
                break;
        }
    }



    private void urgentOn(){
        if(Constatus.URGENT_TYPE){
            Constatus.URGENT_TYPE=false;
            btn_urgentOn.setText("开启紧急模式");
            Toast.makeText(getApplicationContext(),"紧急模式已关闭",
                    Toast.LENGTH_SHORT).show();
        }else{
            Constatus.URGENT_TYPE=true;
            btn_urgentOn.setText("关闭紧急模式");
            Toast.makeText(getApplicationContext(),"请注意!紧急模式已开启!",
                    Toast.LENGTH_SHORT).show();
        }
        sendLoginBroadcast();
    }

    private void clearSqlite(final Class<?> cal , String msg){
        CustomDialog dialog=new CustomDialog(UrgentSetActivity.this,
                msg, new CustomDialog.DialogClickListener() {
            @Override
            public void onDialogClick(int btn) {
                if(btn==1){
                    try {
                            DataSupport.deleteAll(cal);
                        Toast.makeText(getApplicationContext(),"清除成功",
                                Toast.LENGTH_SHORT).show();
                    }catch (Exception e){
                        Toast.makeText(getApplicationContext(),"清除失败",
                                Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }
                }
            }
        });

        dialog.show();
    }

   /**提交午餐信息*/
    private void pushLunch(){
        network();

        if(httpTools==null){
            httpTools=new HttpTools(getApplicationContext(),60*1000);
        }
//        long sysTime=System.currentTimeMillis();
//        String date= SysTimeManage.getInstage().getDate(sysTime);

//        Cursor cursor = DataSupport.findBySQL
//                ("select * from SettletmentBean where commentcount>?", "0");

        ArrayList<SettletmentBean> settleList= (ArrayList<SettletmentBean>)
                DataSupport.where("submit=?","0").find(SettletmentBean.class);
//        Log.e("lh", "settleList.size "+settleList.size());

        if(settleList.size()<=0){
            Toast.makeText(getApplicationContext(),"本地未查询到没有提交的记录",
                    Toast.LENGTH_SHORT).show();
        return;
        }
//        delFile();
        Gson gson=new Gson();
        String data=gson.toJson(settleList);
//        writeTxtToFile(data);

        isLunch=true;
        httpTools.backupdealOrder(token,data,settleList.size(),new JsonPushLunch());
    }

    /**获得取餐信息*/
    private void getMakemealInfo(){
        network();
//        httpTools.getOrders();
        if(httpTools==null){
            httpTools=new HttpTools(getApplicationContext());
        }
        httpTools.backupgetOrders(token,new JsonGetOrder());

    }
    /**上传取餐信息*/
    private void pushMakemeal(){
        network();
        if(httpTools==null){
            httpTools=new HttpTools(getApplicationContext(),60*1000);
        }

        ArrayList<OrderBean> orderList= (ArrayList<OrderBean>)
                DataSupport.where("submit=? ","0").find(OrderBean.class,true);
//        Log.e("lh", "settleList.size "+orderList.size());

        if(orderList.size()<=0){
            Toast.makeText(getApplicationContext(),"本地未查询到没有提交的记录",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        Gson gson=new Gson();
        String data=gson.toJson(orderList);
//        Log.e("lh", "order=="+data);
//        try {
//            int len= data.getBytes("UTF-8").length/1024;
//            Log.e("lh", "len== "+len +"kb" );
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        httpTools.backupdealSorder(token,data,orderList.size(),new JsonPushMakemeal());
    }

      /**网络判断*/
    private void network(){
        if(NetWorkUtil.isNetwork(getApplicationContext())==false)
        {
            btn_pushLunch.setClickable(true);
            Toast.makeText(getApplicationContext(),"当前网络不可用",
                    Toast.LENGTH_SHORT).show();
            return;
        }
    }

    private  class  JsonGetOrder extends JsonHttpResponseHandler {
        @Override
        public void onStart() {
            super.onStart();
            MyShowDialog.showLoadingDialog(UrgentSetActivity.this, "数据获取中.");
            super.onStart();
        }
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            MyShowDialog.closeLoadingDialog();
//            Log.e("lh", "getMakemealInfo=="+response.toString());
            try {
                boolean code= response.getBoolean("code");
                if(code==true){
                    //删除数据库表中的所有数据
                    DataSupport.deleteAll(OrderBean.class);

                    Gson gson=new Gson();
                    BaseOrder order=gson.fromJson(response.toString(),BaseOrder.class);
                    ArrayList<OrderBean> list=order.getData();
                    Gson gson1=new Gson();
                    String srt=gson1.toJson(list);
//                    Log.e("lh","srt=="+srt);
                    //                    DataSupport.saveAll(list);
                    for (OrderBean o:list){
//                        Log.e("lh", "0: "+o.toString());
//                        o.toString();
                        o.save();
                        for(OrderDetail d:o.getDetails()){
                            d.save();
                        }
                    }

                    Toast.makeText(getApplicationContext(),"获取取餐信息成功",
                            Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                Toast.makeText(getApplicationContext(),"获取取餐信息失败，请重新获取",
                        Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable e) {
            super.onFailure(statusCode, headers, responseBody, e);
            MyShowDialog.closeLoadingDialog();
            Toast.makeText(getApplicationContext(),"网络请求超时，请重新获取",
                    Toast.LENGTH_SHORT).show();
        }
    }

    private class JsonPushLunch extends JsonHttpResponseHandler {
        @Override
        public void onStart() {
            super.onStart();
            MyShowDialog.showLoadingDialog(UrgentSetActivity.this, "数据上传中.");
            super.onStart();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            MyShowDialog.closeLoadingDialog();
//            Log.e("lh", "JsonPushLunch=="+response.toString());
            try {
                boolean code= response.getBoolean("code");
                String msg=response.getString("msg");
                if(code==true){
                    ContentValues values=new ContentValues();
                    values.put("submit",1);
                    DataSupport.updateAll(SettletmentBean.class,values,"submit=?","0");
                }else{

                }
                Toast.makeText(getApplicationContext(),msg,
                        Toast.LENGTH_SHORT).show();
            } catch (JSONException e) {

                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable e) {
            super.onFailure(statusCode, headers, responseBody, e);
            MyShowDialog.closeLoadingDialog();
//            Log.e("lh", "statusCode=="+statusCode );
//            Log.e("lh", "responseBody=="+responseBody );
            Toast.makeText(getApplicationContext(),"网络请求超时，请提交获取",
                    Toast.LENGTH_SHORT).show();
        }
    }

    private class JsonPushMakemeal extends JsonHttpResponseHandler {

        @Override
        public void onStart() {
            super.onStart();
            MyShowDialog.showLoadingDialog(UrgentSetActivity.this, "数据上传中.");
            super.onStart();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            MyShowDialog.closeLoadingDialog();
//            Log.e("lh", "JsonPushMakemeal=="+response.toString());
            try {
                boolean code= response.getBoolean("code");
                String msg=response.getString("msg");
                if(code==true){
                    ContentValues values=new ContentValues();
                    values.put("submit",1);
                    DataSupport.updateAll(OrderBean.class,values,"submit=?","0");
                }else{

                }
                Toast.makeText(getApplicationContext(),msg,
                        Toast.LENGTH_SHORT).show();
            } catch (JSONException e) {

                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable e) {
            super.onFailure(statusCode, headers, responseBody, e);
            MyShowDialog.closeLoadingDialog();
//            Log.e("lh", "statusCode=="+statusCode );
//            Log.e("lh", "responseBody=="+responseBody );
            Toast.makeText(getApplicationContext(),"网络请求超时，请提交获取",
                    Toast.LENGTH_SHORT).show();
        }
    }


    //向整个应用发送登陆广播事件 ，局部广播，局部广播安全
    private void sendLoginBroadcast() {
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(LOGIN_ACTION));
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    |View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    |View.SYSTEM_UI_FLAG_FULLSCREEN);
        }
    }

    //    private void createFile(){
//        sqlfile =new File(file_path);
//        //如果该文件夹不存在，则进行创建
//        if(!sqlfile.exists()){
//            sqlfile.mkdirs();//创建文件夹
//        }
//    }
    /**创建TXT文件*/
//    private File createFileName(){
//        long sysTime=System.currentTimeMillis();
//        String file_name=SysTimeManage.getInstage().getYMD(sysTime)+"/"+"123";
//        String strFilePath=file_path+file_name;
//        File filename=new File(strFilePath);
//        if(!sqlfile.exists()){
//            try {
//                filename.createNewFile(); //生成文件
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return  filename;
//    }

    //删除文件
//    public  void delFile(){
////        String strFilePath=file_path+file_name;
////        File file = new File(strFilePath);
//        if(createFileName().isFile()){
//            createFileName().delete();
//        }
//        createFileName().exists();
//    }

//    private void writeTxtToFile(String context){
//        try {
//            RandomAccessFile raf=new RandomAccessFile(createFileName(),"rwd");
//            raf.seek(createFileName().length());
//            raf.write(context.getBytes());
//            raf.close();
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//    }
}
